part of '../repository.dart';

const _kSubscriptionDurationKey = 'duration';

const _kSubscriptionTypeValue = 'subscription';

class _SubscriptionDto extends Equatable implements _PurchaseItemDto {
  const _SubscriptionDto._internal({
    required this.sku,
    required this.priceDto,
    required this.title,
    required this.legacy,
    required this.durationDto,
  });

  @override
  final String sku;

  @override
  final _MoneyAmountDto priceDto;

  @override
  final String title;

  @override
  final bool legacy;

  final _SubscriptionDurationDto durationDto;

  @override
  List<Object?> get props {
    return [
      sku,
      priceDto,
      title,
      legacy,
      durationDto,
    ];
  }

  @override
  String get type => _kSubscriptionTypeValue;

  factory _SubscriptionDto.fromJson(Map<String, dynamic> json) {
    final priceJson = json[_kPurchaseItemPriceKey];
    final priceDto = _MoneyAmountDto.fromJson(priceJson);

    final durationString = json[_kSubscriptionDurationKey];
    final durationDto = _SubscriptionDurationDto.fromString(durationString);

    return _SubscriptionDto._internal(
      sku: json[_kPurchaseItemSkuKey],
      priceDto: priceDto,
      title: json[_kPurchaseItemTitleKey],
      legacy: json[_kPurchaseItemLegacyKey],
      durationDto: durationDto,
    );
  }

  // factory _SubscriptionDto.fromEntity(WebSubscription subscription) {
  //   final priceDto = _MoneyAmountDto.fromEntity(subscription.price);
  //   final durationDto = _SubscriptionDurationDto.fromEntity(subscription.duration);
  //
  //   return _SubscriptionDto._internal(
  //     sku: subscription.sku,
  //     priceDto: priceDto,
  //     title: subscription.title,
  //     legacy: subscription.legacy,
  //     durationDto: durationDto,
  //   );
  // }

  @override
  Map<String, dynamic> toJson() {
    return {
      _kPurchaseItemTypeKey: type,
      _kPurchaseItemSkuKey: sku,
      _kPurchaseItemPriceKey: priceDto.toJson(),
      _kPurchaseItemTitleKey: title,
      _kPurchaseItemLegacyKey: legacy,
      _kSubscriptionDurationKey: durationDto.toString(),
    };
  }

  @override
  WebSubscription toEntity() {
    return WebSubscription(
      sku: sku,
      price: priceDto.toEntity(),
      title: title,
      legacy: legacy,
      duration: durationDto.toEntity(),
    );
  }
}
